var fs = require('fs'),
    path = require('path');
const mingo = require('./common/mongoapi')

const rank = async (type, content, id) => {
    if (type == 'set') {
        content.openid = id;
        content.time -= 0;
        let data = new Promise((resolve, reject) => {
            mingo.findOne('ranks', id, (data) => {
                if (!!data) resolve(data)
                else resolve(null)
            })
        })
        let ranks = await data;
        if (ranks == null) {
            let insert = new Promise((resolve, reject) => {
                mingo.insert('ranks', content, (data) => {
                    if (!!data) resolve(data)
                    else resolve(null)
                })
            })
            await insert;
        } else {
            if (data.time > content.time) {
                let update = new Promise((resolve, reject) => {
                    mingo.update('ranks', id, content, (data) => {
                        if (!!data) resolve(data)
                        else resolve(null)
                    })
                })
                await update;
            }
        }
        return {
            success: "1",
            content: {
                set: '设置成功'
            }
        }
    }
    else {
        let data2 = new Promise((resolve, reject) => {
            mingo.findAll('ranks', { "time": 1 }, 10, (data) => {
                if (data && !!data.length) resolve(data)
                else resolve([])
            })
        })
        let data2Result = await data2;
        let data3 = [];
        for (let i = 0; i <= data2Result.length - 1; i++) {
            let item = data2Result[i];
            let $data = new Promise((resolve, reject) => {
                mingo.findOne('users', item.openid, (data) => {
                    if (!!data) {
                        if (data.openid == id) data.isSelf = true;
                        data.time = item.time;
                        resolve(data)
                    }
                    else reject(new Error('data is empty'))
                })
            })
            let data = await $data;
            data3.push(data)
        }
        return {
            success: "1",
            content: {
                rankData: data3
            }
        }
    }
}

module.exports = rank;